package security.internal;

import java.util.Iterator;
import java.util.Set;

import org.springframework.dao.DataAccessException;
import org.springframework.security.userdetails.UserDetails;
import org.springframework.security.userdetails.UserDetailsService;
import org.springframework.security.userdetails.UsernameNotFoundException;

import project.Constants;
import security.Role;
import security.SecUser;

public class UserDetailsServiceImpl implements UserDetailsService {

    private SecUserService secUserService;

    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException {

        SecUser user = secUserService.findUserByLoginName(username);
        if (user == null) {
            throw new UsernameNotFoundException("找不到用户!", username);
        }
        
        
        Set<Role> roles = user.getRoles();
        boolean find = false;
        for (Iterator iterator = roles.iterator(); iterator.hasNext();) {
            Role role = (Role) iterator.next();
            if (role.getRoleName().equals(Constants.SECURITY_ROLE_MEMBER)) {
                find = true;
            }

        }
        if (!find) {
            throw new UsernameNotFoundException("找不到用户!", username);
        }
        return user;

    }

    public void setSecUserService(SecUserService secUserService) {
        this.secUserService = secUserService;
    }

}
